<template>
  <div class="container">
    <van-sticky :offset-top="0">
      <van-nav-bar
        left-text="返回"
        :title="products[0] ? products[0].category.name : '分类'"
        left-arrow
        @click-left="back"
      />
    </van-sticky>
    <van-tabs
      @click="onClick"
      animated
      type="card"
      style="width: 100%; position: fixed; z-index: 999"
    >
      <van-tab title="随机"></van-tab>
      <van-tab title="价格 ↑"></van-tab>
      <van-tab title="价格 ↓"></van-tab>
    </van-tabs>

    <div class="catep">
      <van-card
        v-for="i in products"
        :key="i.id"
        :num="i.quantity"
        :tag="i.category.name"
        :price="i.price"
        :title="i.name"
        :thumb="i.coverImage"
        origin-price="199.00"
        :thumb-link="'/#/pdetail?id=' + i.id"
      >
        <template #footer>
          <van-button
            size="small"
            icon="cart-o"
            type="danger"
            @click="buyit(i.id)"
          ></van-button>
        </template>
      </van-card>
    </div>
  </div>
</template>

<script>
import { loadPCategories } from "../services/categroies";
import { addToCart } from "../services/cart";
import { isLogined } from "../utils/tools";
import { Toast } from "vant";
export default {
  data() {
    return {
      products: [],
      activeName: "a",
    };
  },
  async created() {
    const res = await loadPCategories(this.$route.params.id);
    console.log(res);
    this.products = res.data;
  },
  methods: {
    back() {
      window.history.go(-1);
    },
    async buyit(id) {
      if (isLogined()) {
        await addToCart(id, 1);
        Toast.success("加入购物车成功");
        this.$router.push({
          name: "Cart",
        });
      }
    },
    onClick(name, title) {
      console.log(name);
      const res = this.products;
      if (title == "随机") {
        this.products = res.sort(() => Math.random() - 0.5);
      } else if (title == "价格 ↑") {
        this.products = res.sort((a, b) => a.price - b.price);
      } else if (title == "价格 ↓") {
        this.products = res.sort((a, b) => b.price - a.price);
      }
    },
  },
};
</script>

<style scoped>
.catep {
  padding-top: 2.5rem;
}
</style>